package com.fat.spzx.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.fat.spzx.common.constans.RedisConstans;
import com.fat.spzx.model.entity.system.SysUser;
import com.fat.spzx.model.vo.common.Result;
import com.fat.spzx.model.vo.common.ResultCodeEnum;
import com.fat.spzx.utils.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     *  在执行目标方法之前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求方式
        String method = request.getMethod();
        //判断是否是OPTIONS请求，如果是则放行
        if ("OPTIONS".equalsIgnoreCase(method)) return true;

        //2.从请求头获取token
        String token = request.getHeader("token");

        //3.判断token是否为空
        if (StrUtil.isEmpty(token)){
            //响应208状态码给前端
            responseNoLoginInfo(response);
            return false;
        }

        //4.不为空，判断redis中是否存在该token
        String userJson = redisTemplate.opsForValue().get(RedisConstans.USER_LOGIN+token);

        //5.判断userJson是否为空
        if (StrUtil.isEmpty(userJson)) {
            //响应208状态码给前端
            responseNoLoginInfo(response);
            return false;
        }

        //6.不为空，将userJson转为对象放入Thread Local中
        AuthContextUtil.setUser(JSON.parseObject(userJson, SysUser.class));

        //7.更新redis中的token的有效期
        redisTemplate.expire(RedisConstans.USER_LOGIN+token,30, TimeUnit.MINUTES);

        //8.放行
        return true;
    }

    /**
     * 在执行目标方法之后执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除用户信息
        AuthContextUtil.removeUser();
    }


    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }
}
